<template>
  <div class="commentbox">
    <el-form ref="form" :model="form">
      <el-form-item>
        <el-input type="textarea" v-model="form.comment"></el-input>
        <div class="tool-box">
          <el-button class="comment-btn" type="primary" @click="onSubmit">评论</el-button>
          <div class="user-info"  v-if="is_login == true">
            <img class="avatar" :src="user.figureurl" />
            <span class="nickname">{{user.nickname}}</span>
            <a class="logout" href="javascript:;" v-on:click="logout">退出</a>
          </div>

          <el-button v-if="is_login == false" class="qq_login" @click="qq_login"><img src="http://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png"></el-button>
        </div>
      </el-form-item>
    </el-form>
    <div class="comment-centent">
      <div class="content">
        <ul>
          <li v-for="comment in commentList" :key="comment.id">
            <p>{{comment.comment}}</p>
            <p class="date">{{comment.create_time}}</p>
            <p class="nickname"><img :src="comment.figureurl" />{{comment.nickname}}</p>
          </li>
        </ul>        
      </div>

      <div class="pagination">
        <el-pagination
          v-if="total > page_size"
          layout="total, prev, pager, next"
          @current-change="skipPage"
          :page-size="page_size"
          :total="total">
        </el-pagination>
      </div>
    </div>

    <!--弹窗-->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      size="large"
      :before-close="handleClose">
      <span>已经打开qq登录页面，是否确认qq已经登录？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">容我考虑下</el-button>
        <el-button type="primary" @click="qq_login_success">已经登录</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
import md5 from 'js-md5';

export default {
  name: 'commentbox',
  props:['id'],
  data () {
    return {
      commentList: [],
      uid: 1,
      form:{
        comment:''
      },
      page_size: 1,
      total: 1,
      is_login: false,
      user: [],
      dialogVisible:false,
    }
  },
  created: function(){
    this.get_user();
  },
  methods: {
    fetchData(){
      this.getComment();
    },
    skipPage(page){
      this.getComment(page);
    },
    onSubmit(){
      if(this.form.comment.replace(/^\s+|\s+$/gm,'') == ''){
        this.$message.error('发表的内容不能为空！');
        return;
      }

      var that = this;
      var user_token = this.get_user_token();
      this.$http.post('/api/comment/comment', {article_id:this.id,token:user_token,comment:this.form.comment}).then(function(result){
        if(result.body.status == 200){
          this.$message({
            message: result.body.msg,
            type: 'success'
          });
          that.getComment();
        }else{
          this.$message.error( result.body.msg );
        }
      });

    },
    getComment(page = 1){
      this.$http.post('/api/comment/index', {article_id:this.id,page:page}).then(function(result){
        this.commentList = result.body.data.list;
        this.page_size = result.body.data.page_size;
        this.total = result.body.data.total;
      });
    },
    qq_login(){
      var user_token = this.get_user_token();
      this.dialogVisible = true;
      var A=window.open("http://www.fy1994.cn/example/oauth/index.php?user_token="+user_token);
    },
    qq_login_success(){
      this.get_user();
      this.dialogVisible = false;
    },
    //判断用户登录过没有
    get_user(){
      var user_token = this.get_user_token();
      this.$http.post('/api/user/info', {token: user_token}).then(function(result){
        if(result.body.status == 200){
          this.is_login = true;
          this.user = result.body.data;
        }else{
          console.log( result.body.data );
        }
      });
    },
    logout(){
      this.is_login = false;
      this.delCookie("user_token");
    },
    get_user_token(){
      var user_token = '';
      if(this.getCookie('user_token') == null){
        var timestamp = Date.parse(new Date()); 
        user_token = md5(timestamp+Math.random()*99999+this.uuid(10,16));
        this.setCookie('user_token', user_token);
      }else{
        user_token = this.getCookie('user_token');
      }

      return user_token;
    },
    handleClose(done) {
      this.dialogVisible = false;
      // this.$confirm('qq登录后需要刷新页面才能展示登录信息？')
      //   .then(_ => {
      //     done();
      //   })
      //   .catch(_ => {});
    },
    getCookie(name){
      var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
      if(arr=document.cookie.match(reg))
      return unescape(arr[2]);
      else
      return null;
    },
    setCookie(name,value){
      var Days = 30;
      var exp = new Date();
      exp.setTime(exp.getTime() + Days*24*60*60*1000);
      document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
    },
    delCookie(name)
    {
      var date = new Date(); //获取当前时间
      date.setTime(date.getTime()-10000); //将date设置为过去的时间
      document.cookie = name + "=v; expires =" +date.toGMTString();//设置cookie
    },
    uuid(len, radix) {
      var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
      var uuid = [], i;
      radix = radix || chars.length;
      
      if (len) {
       // Compact form
       for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
      } else {
       // rfc4122, version 4 form
       var r;
      
       // rfc4122 requires these characters
       uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
       uuid[14] = '4';
      
       // Fill in random data. At i==19 set the high bits of clock sequence as
       // per rfc4122, sec. 4.1.5
       for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
         r = 0 | Math.random()*16;
         uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
       }
      }
      
      return uuid.join('');
    }

  },
  watch:{
    "id": "fetchData"
  } 
}

</script>

<style type="text/css">
  .commentbox .tool-box{margin-top: 10px;}
  .commentbox .el-form{padding: 20px;padding-bottom: 0px;}
  .commentbox .el-form-item{margin-bottom: 0px;}
  .comment-centent{padding-bottom: 30px;}
  .comment-centent .content ul{list-style: none;padding: 0px 10px;}
  .comment-centent .content li{overflow: hidden;zoom: 1;border-bottom: 1px dashed #e5e5e5;padding: 5px;}
  .commentbox .content{padding: 5px;}
  .commentbox .nickname{float: right;color: #959595;padding-top: 5px;}
  .commentbox .date{float: left;color: #959595;padding-top: 5px;}
  .commentbox .pagination{text-align: center;}
  .commentbox .qq_login{padding: 4px;float: right;}
  .commentbox .user-info{float: right;padding-left: 10px;margin-top: 3px;}
  .commentbox .user-info .avatar{height: 30px;width: 30px;float: left;}
  .commentbox .user-info .nickname{float: left;height: 30px;line-height: 30px;padding-top: 0px;font-size: 16px;margin-left: 10px;color: #333;}
  .commentbox .comment-btn{float: left;}
  .nickname img{width: 20px;height: 20px;border-radius: 50%;float: right;margin-top: 1px;margin-left:5px;}
  .logout{position: absolute;right: 0px;bottom: -20px;}

  @media screen and (min-width: 500px) {
    .el-dialog--large{max-width: 28%;}
  }

  
</style>